const jwt = require('jsonwebtoken');
const config = require('../config');
module.exports = async (ctx, next) => {
  const authorization = ctx.get('Authorization');
  if (!authorization || !authorization.startsWith('Bearer ')) {
      ctx.status = 401;
      ctx.body = { success: false, message: 'Token expired, please save your data locally' };
      return;
  }

  const token = authorization.split(' ')[1];

  try {
      const tokenContent = await jwt.verify(token, config.jwt.secret);
      ctx.user = tokenContent;
      await next(); // 继续执行后续的路由处理
  } catch (err) {
    console.log('22121212', err);
      if (err.name === 'TokenExpiredError') {
          ctx.throw(401, 'Token expired, please save your data locally!');
      } else {
        throw err // 抛出错误，以便后续处理
      }
  }
};